<template>
  <editor-layout class="edit" @ok="handleOk" v-on="$listeners" v-loading="loading" :loading="saveLoading">
    <el-form size="small" :model="model" :rules="rule" ref="form" @keyup.enter.native="handleOk()" label-width="110px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="数据源类型" prop="sourceType">
            <report-select v-model="model.sourceType" type="SOURCE_TYPE" @change="onSourceTypeChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数据源名称" prop="sourceName">
            <el-input v-model.trim="model.sourceName" clearable/>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="数据源描述">
            <el-input
                v-model.trim="model.sourceDesc"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col
            v-for="(data, index) in dataLink"
            :key="index"
            :span="24"
        >
          <el-form-item :label="data.labelValue">
            <el-input v-model.trim="data.value"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button size="small" @click="handleCancel">取消</el-button>
      <el-button size="small" type="warning" @click="handleTest">测试</el-button>
      <el-button :loading="saveLoading" size="small" type="primary" @click="handleOk">确定</el-button>
    </template>
  </editor-layout>
</template>


<script>
import {postReportReportdatasourceSave,
  postReportReportdatasourceUpdate,
  getReportReportdatasourceInfoId,
  postReportReportdatasourceTestConnection} from '@/api/dataSource'
import {postReportDictitemListAll} from '@/api/dict'

export default {
  name: 'edit',
  props: {
    id: [String, Number]
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      model: {
        sourceType: '',
        sourceName: '',
        sourceDesc: '',
        sourceConfig: ''
      },
      rule: {
        sourceType: [{required: true, message: '必填项'}],
        sourceName: [{required: true, message: '必填项'}]
      },
      sourceList: [],
      dataLink: [],
      isTestOk: false
    }
  },
  methods: {
    async init() {
      await this.getSystemDict()
      if (this.id) {
        this.loadForm()
      }
    },
    async loadForm() {
      this.loading = true
      const data = await getReportReportdatasourceInfoId(this.id).catch(e => {
        this.loading = false
        throw new Error(e)
      })
      this.model = data
      let newDataLink = []
      const findType = this.sourceList.find(o => o.itemValue === data.sourceType)
      if (findType) {
        newDataLink = JSON.parse(findType.itemExtend)
        if (data.sourceConfig) {
          const sourceConfigJson = JSON.parse(data.sourceConfig)
          for (let i = 0; i < newDataLink.length; i++) {
            newDataLink[i].value = sourceConfigJson[newDataLink[i].label];
          }
        }
      }

      this.dataLink = newDataLink
      this.loading = false
    },
    async getSystemDict() {
      // 数据源类型
      const res = await postReportDictitemListAll({enabled: 1, locale: 'zh', dictCode: 'SOURCE_TYPE'})
      this.sourceList = res || []
      this.model.sourceType = res[0].itemValue
      this.dataLink = JSON.parse(this.sourceList[0].itemExtend)
    },
    onSourceTypeChange(val) {
      this.dataLink = []
      const extendJSON = this.sourceList.find(obj => obj.itemValue === val)
      this.dataLink = JSON.parse(extendJSON.itemExtend)
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleTest() {
      const newList = {};
      this.dataLink.forEach(item => {
        newList[item.label] = item.value;
      });
      this.model.sourceConfig = JSON.stringify(newList);

      postReportReportdatasourceTestConnection(this.model).then(res => {
        this.isTestOk = res
        this.$message({
          message: '测试成功！',
          type: 'success'
        })
      })
    },
    handleOk() {
      this.$refs.form.validate(ok => {
        if (!ok) return

        if(!this.isTestOk) {
          this.$message.error('测试结果为成功后方可保存！');
          return
        }

        const newList = {};
        this.dataLink.forEach(item => {
          newList[item.label] = item.value;
        })
        const param = {...this.model}
        param.sourceConfig = JSON.stringify(newList)

        let fn = postReportReportdatasourceSave
        if (this.id || this.model.id) {
          fn = postReportReportdatasourceUpdate
        }
        this.saveLoading = true

        fn(param).then(res => {
          this.$notify.success('操作成功!')
          this.$emit('on-ok')
        })
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>


